<template>
  <div class="attendance-records-container">
    <!-- 详情视图 -->
    <div v-if="isDetailMode" class="attendance-record-detail">
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>考勤记录详情</span>
            <el-button type="primary" @click="backToList">返回列表</el-button>
          </div>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工号">{{ recordDetail.employee_id }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ recordDetail.employee_name }}</el-descriptions-item>
          <el-descriptions-item label="日期">{{ recordDetail.date }}</el-descriptions-item>
          <el-descriptions-item label="星期">{{ recordDetail.weekday }}</el-descriptions-item>
          <el-descriptions-item label="考勤类型">
            <el-tag :type="getAttendanceTypeTagType(recordDetail.attendance_type_id)">
              {{ getAttendanceTypeName(recordDetail.attendance_type_id) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="加班类型">
            <el-tag :type="getOvertimeTypeTagType(recordDetail.overtime_type)">
              {{ getOvertimeTypeName(recordDetail.overtime_type) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>工时详情</el-divider>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="早上上班">{{ recordDetail.morning_on_duty }}</el-descriptions-item>
          <el-descriptions-item label="中午下班">{{ recordDetail.noon_off_duty }}</el-descriptions-item>
          <el-descriptions-item label="下午下班">{{ recordDetail.afternoon_off_duty }}</el-descriptions-item>
          <el-descriptions-item label="晚上下班">{{ recordDetail.night_off_duty }}</el-descriptions-item>
          <el-descriptions-item label="中午工时">{{ recordDetail.noon_work_hours }}</el-descriptions-item>
          <el-descriptions-item label="下午工时">{{ recordDetail.afternoon_work_hours }}</el-descriptions-item>
          <el-descriptions-item label="白班总工时">{{ recordDetail.day_total_work_hours }}</el-descriptions-item>
          <el-descriptions-item label="晚上工时">{{ recordDetail.night_work_hours }}</el-descriptions-item>
          <el-descriptions-item label="加班工时">{{ recordDetail.overtime_hours }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
    
    <!-- 列表视图 -->
    <div v-else>
      <!-- 顶部操作栏 -->
      <div class="operation-bar">
        <div class="left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增考勤记录
          </el-button>
          <el-upload
            class="excel-upload"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            accept=".xlsx,.xls"
            @change="handleExcelChange"
          >
            <el-button type="success">
              <el-icon><Upload /></el-icon>导入Excel
            </el-button>
          </el-upload>
          <el-button type="warning" @click="handleExport">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
          <el-button type="info" :disabled="!hasSelection" @click="handleBatchEdit">
            <el-icon><Edit /></el-icon>批量编辑
          </el-button>
          <el-button type="danger" :disabled="!hasSelection" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
        </div>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-bar">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item label="员工">
            <el-select
              v-model="selectedEmployee"
              placeholder="选择或输入员工姓名"
              clearable
              filterable
              @change="handleSearch"
              style="width: 200px;"
            >
              <el-option
                v-for="employee in employees"
                :key="employee.employee_id"
                :label="employee.name"
                :value="employee.employee_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="考勤类型">
            <el-select
              v-model="selectedAttendanceType"
              placeholder="选择考勤类型"
              clearable
              @change="handleSearch"
              style="width: 200px;"
            >
              <el-option
                v-for="type in attendanceTypes"
                :key="type.type_id"
                :label="type.type_name"
                :value="type.type_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="加班类型">
            <el-select
              v-model="selectedOvertimeType"
              placeholder="选择加班类型"
              clearable
              @change="handleSearch"
              style="width: 150px;"
            >
              <el-option label="无加班" :value="0" />
              <el-option label="1.5倍" :value="1.5" />
              <el-option label="2倍" :value="2" />
              <el-option label="3倍" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 考勤记录列表 -->
      <el-table
        v-loading="loading"
        :data="paginatedRecords"
        style="width: 100%"
        border
        height="calc(100% - 180px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="record_id" label="ID" width="80" />
        <el-table-column prop="employee_id" label="工号" width="120" />
        <el-table-column prop="employee_name" label="姓名" width="120" />
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="weekday" label="星期" width="80" />
        <el-table-column prop="morning_on_duty" label="早上上班" width="120" />
        <el-table-column prop="noon_off_duty" label="中午下班" width="120" />
        <el-table-column prop="afternoon_off_duty" label="下午下班" width="120" />
        <el-table-column prop="night_off_duty" label="晚上下班" width="120" />
        <el-table-column prop="noon_work_hours" label="中午工时" width="100" />
        <el-table-column prop="afternoon_work_hours" label="下午工时" width="100" />
        <el-table-column prop="day_total_work_hours" label="白班总工时" width="120" />
        <el-table-column prop="night_work_hours" label="晚上工时" width="100" />
        <el-table-column prop="overtime_hours" label="加班工时" width="100" />
        <el-table-column label="考勤类型" width="120">
          <template #default="scope">
            {{ getAttendanceTypeName(scope.row.attendance_type_id) }}
          </template>
        </el-table-column>
        <el-table-column label="加班类型" width="100">
          <template #default="scope">
            {{ getOvertimeTypeName(scope.row.overtime_type) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增考勤记录' : '编辑考勤记录'"
        width="800px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工" prop="employee_id">
                <el-select
                  v-model="form.employee_id"
                  placeholder="选择员工"
                  style="width: 100%"
                >
                  <el-option
                    v-for="employee in employees"
                    :key="employee.employee_id"
                    :label="employee.name"
                    :value="employee.employee_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日期" prop="date">
                <el-date-picker
                  v-model="form.date"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="updateWeekday"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="星期" prop="weekday">
                <el-input v-model="form.weekday" placeholder="星期几" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考勤类型" prop="attendance_type_id">
                <el-select
                  v-model="form.attendance_type_id"
                  placeholder="选择考勤类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="type in attendanceTypes"
                    :key="type.type_id"
                    :label="type.type_name"
                    :value="type.type_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="早上上班" prop="morning_on_duty">
                <el-time-picker
                  v-model="form.morning_on_duty"
                  placeholder="选择时间"
                  style="width: 100%"
                  format="HH:mm"
                  value-format="HH:mm"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中午下班" prop="noon_off_duty">
                <el-time-picker
                  v-model="form.noon_off_duty"
                  placeholder="选择时间"
                  style="width: 100%"
                  format="HH:mm"
                  value-format="HH:mm"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="下午下班" prop="afternoon_off_duty">
                <el-time-picker
                  v-model="form.afternoon_off_duty"
                  placeholder="选择时间"
                  style="width: 100%"
                  format="HH:mm"
                  value-format="HH:mm"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="晚上下班" prop="night_off_duty">
                <el-time-picker
                  v-model="form.night_off_duty"
                  placeholder="选择时间"
                  style="width: 100%"
                  format="HH:mm"
                  value-format="HH:mm"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="中午工时" prop="noon_work_hours">
                <el-input-number
                  v-model="form.noon_work_hours"
                  :precision="1"
                  :step="0.5"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下午工时" prop="afternoon_work_hours">
                <el-input-number
                  v-model="form.afternoon_work_hours"
                  :precision="1"
                  :step="0.5"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="白班总工时" prop="day_total_work_hours">
                <el-input-number
                  v-model="form.day_total_work_hours"
                  :precision="1"
                  :step="0.5"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="晚上工时" prop="night_work_hours">
                <el-input-number
                  v-model="form.night_work_hours"
                  :precision="1"
                  :step="0.5"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="加班工时" prop="overtime_hours">
                <el-input-number
                  v-model="form.overtime_hours"
                  :precision="1"
                  :step="0.5"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="加班类型" prop="overtime_type">
                <el-select
                  v-model="form.overtime_type"
                  placeholder="选择加班类型"
                  style="width: 100%"
                >
                  <el-option label="无加班" :value="0" />
                  <el-option label="1.5倍" :value="1.5" />
                  <el-option label="2倍" :value="2" />
                  <el-option label="3倍" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="400px"
      >
        <p>确定要删除这条考勤记录吗？此操作不可恢复。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDelete">确定删除</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批量编辑对话框 -->
      <el-dialog
        v-model="batchEditDialogVisible"
        title="批量编辑考勤记录"
        width="600px"
      >
        <el-form
          ref="batchFormRef"
          :model="batchForm"
          label-width="120px"
        >
          <el-form-item label="选中记录">
            <span>{{ multipleSelection.length }}条记录</span>
          </el-form-item>
          
          <el-divider content-position="center">选择要批量修改的字段</el-divider>
          
          <el-form-item>
            <el-checkbox v-model="batchFields.attendanceType">考勤类型</el-checkbox>
            <el-checkbox v-model="batchFields.overtimeType">加班类型</el-checkbox>
            <el-checkbox v-model="batchFields.workHours">工时</el-checkbox>
            <el-checkbox v-model="batchFields.dutyTimes">上下班时间</el-checkbox>
          </el-form-item>
          
          <el-form-item label="考勤类型" v-if="batchFields.attendanceType">
            <el-select
              v-model="batchForm.attendance_type_id"
              placeholder="选择考勤类型"
              style="width: 100%"
            >
              <el-option
                v-for="type in attendanceTypes"
                :key="type.type_id"
                :label="type.type_name"
                :value="type.type_id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="加班类型" v-if="batchFields.overtimeType">
            <el-select
              v-model="batchForm.overtime_type"
              placeholder="选择加班类型"
              style="width: 100%"
            >
              <el-option label="无加班" :value="0" />
              <el-option label="1.5倍" :value="1.5" />
              <el-option label="2倍" :value="2" />
              <el-option label="3倍" :value="3" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="工时相关" v-if="batchFields.workHours">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="中午工时">
                  <el-input-number
                    v-model="batchForm.noon_work_hours"
                    :precision="1"
                    :step="0.5"
                    :min="0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下午工时">
                  <el-input-number
                    v-model="batchForm.afternoon_work_hours"
                    :precision="1"
                    :step="0.5"
                    :min="0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="白班总工时">
                  <el-input-number
                    v-model="batchForm.day_total_work_hours"
                    :precision="1"
                    :step="0.5"
                    :min="0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="晚上工时">
                  <el-input-number
                    v-model="batchForm.night_work_hours"
                    :precision="1"
                    :step="0.5"
                    :min="0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="加班工时">
                  <el-input-number
                    v-model="batchForm.overtime_hours"
                    :precision="1"
                    :step="0.5"
                    :min="0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          
          <el-form-item label="上下班时间" v-if="batchFields.dutyTimes">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="早上上班">
                  <el-time-picker
                    v-model="batchForm.morning_on_duty"
                    placeholder="选择时间"
                    style="width: 100%"
                    format="HH:mm"
                    value-format="HH:mm"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="中午下班">
                  <el-time-picker
                    v-model="batchForm.noon_off_duty"
                    placeholder="选择时间"
                    style="width: 100%"
                    format="HH:mm"
                    value-format="HH:mm"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="下午下班">
                  <el-time-picker
                    v-model="batchForm.afternoon_off_duty"
                    placeholder="选择时间"
                    style="width: 100%"
                    format="HH:mm"
                    value-format="HH:mm"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="晚上下班">
                  <el-time-picker
                    v-model="batchForm.night_off_duty"
                    placeholder="选择时间"
                    style="width: 100%"
                    format="HH:mm"
                    value-format="HH:mm"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="batchEditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmBatchEdit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批量删除确认对话框 -->
      <el-dialog
        v-model="batchDeleteDialogVisible"
        title="确认批量删除"
        width="400px"
      >
        <p>确定要删除选中的 {{ multipleSelection.length }} 条考勤记录吗？此操作不可恢复。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmBatchDelete">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { Plus, Upload, Download, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAttendanceStore } from '@/stores/attendance'
import { useEmployeeStore } from '@/stores/employee'
import { useAttendanceTypeStore } from '@/stores/attendanceType'
import { useExcelImport } from '@/hooks/useExcelImport'
import type { FormInstance, FormRules } from 'element-plus'
import { storeToRefs } from 'pinia'
import type { AttendanceRecord } from '@/types/attendance'
import type { Employee } from '@/types/employee'
import * as XLSX from 'xlsx'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

// 状态管理
const attendanceStore = useAttendanceStore()
const employeeStore = useEmployeeStore()
const attendanceTypeStore = useAttendanceTypeStore()
const { attendanceRecords, loading, totalRecords } = storeToRefs(attendanceStore)
const { employees } = storeToRefs(employeeStore)
const { attendanceTypes } = storeToRefs(attendanceTypeStore)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

// 筛选相关
const dateRange = ref<[string, string] | null>(null)
const selectedEmployee = ref('')
const selectedAttendanceType = ref<number | null>(null)
const selectedOvertimeType = ref<number | null>(null)
const originalRecords = ref<AttendanceRecord[]>([])

// 计算筛选后的记录
const filteredRecords = computed(() => {
  let result = [...attendanceRecords.value]
  
  // 日期范围筛选
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    const [startDate, endDate] = dateRange.value
    result = result.filter(record => 
      record.date >= startDate && record.date <= endDate
    )
  }
  
  // 员工筛选
  if (selectedEmployee.value) {
    result = result.filter(record => 
      record.employee_id === selectedEmployee.value
    )
  }
  
  // 考勤类型筛选
  if (selectedAttendanceType.value !== null) {
    result = result.filter(record => 
      record.attendance_type_id === selectedAttendanceType.value
    )
  }
  
  // 加班类型筛选
  if (selectedOvertimeType.value !== null) {
    result = result.filter(record => 
      record.overtime_type === selectedOvertimeType.value
    )
  }
  
  // 更新总记录数
  totalRecords.value = result.length
  
  return result
})

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = ref({
  record_id: 0,
  employee_id: '',
  date: '',
  weekday: '',
  morning_on_duty: '',
  noon_off_duty: '',
  afternoon_off_duty: '',
  night_off_duty: '',
  noon_work_hours: 0,
  afternoon_work_hours: 0,
  day_total_work_hours: 0,
  night_work_hours: 0,
  overtime_hours: 0,
  attendance_type_id: 0,
  overtime_type: 0
})

// 删除相关
const deleteDialogVisible = ref(false)
const recordToDelete = ref<AttendanceRecord | null>(null)
const batchDeleteDialogVisible = ref(false)

// 表格多选相关
const multipleSelection = ref<AttendanceRecord[]>([])
const hasSelection = computed(() => multipleSelection.value.length > 0)

// 表单验证规则
const rules = {
  employee_id: [
    { required: true, message: '请选择员工', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  attendance_type_id: [
    { required: true, message: '请选择考勤类型', trigger: 'change' }
  ]
}

// Excel导入
const { readExcelFile, validateImportData } = useExcelImport()

// 获取考勤记录列表
const fetchAttendanceRecords = async () => {
  try {
    await attendanceStore.fetchAttendanceRecords()
    originalRecords.value = [...attendanceStore.attendanceRecords]
  } catch (error) {
    ElMessage.error('获取考勤记录列表失败')
  }
}

// 获取员工列表
const fetchEmployees = async () => {
  if (employees.value.length === 0) {
    await employeeStore.fetchEmployees()
  }
}

// 获取考勤类型列表
const fetchAttendanceTypes = async () => {
  if (attendanceTypes.value.length === 0) {
    await attendanceTypeStore.fetchAttendanceTypes()
  }
}

// 获取考勤类型名称
const getAttendanceTypeName = (typeId: number): string => {
  const type = attendanceTypes.value.find(t => t.type_id === typeId)
  return type ? type.type_name : `未知类型(${typeId})`
}

// 获取加班类型名称
const getOvertimeTypeName = (overtimeType: number): string => {
  switch (overtimeType) {
    case 0: return '无加班'
    case 1.5: return '1.5倍'
    case 2: return '2倍'
    case 3: return '3倍'
    default: return `${overtimeType}倍`
  }
}

// 更新星期几
const updateWeekday = () => {
  if (form.value.date) {
    const date = new Date(form.value.date)
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    form.value.weekday = weekdays[date.getDay()]
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 新增考勤记录
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    record_id: 0,
    employee_id: '',
    date: '',
    weekday: '',
    morning_on_duty: '',
    noon_off_duty: '',
    afternoon_off_duty: '',
    night_off_duty: '',
    noon_work_hours: 0,
    afternoon_work_hours: 0,
    day_total_work_hours: 0,
    night_work_hours: 0,
    overtime_hours: 0,
    attendance_type_id: 0,
    overtime_type: 0
  }
  dialogVisible.value = true
}

// 编辑考勤记录
const handleEdit = (row: AttendanceRecord) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除考勤记录
const handleDelete = (row: AttendanceRecord) => {
  recordToDelete.value = row
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!recordToDelete.value) return
  
  try {
    const success = await attendanceStore.deleteAttendanceRecord(recordToDelete.value.record_id)
    if (success) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      // 刷新数据
      await fetchAttendanceRecords()
    }
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保日期格式统一为 YYYY-MM-DD
        if (form.value.date) {
          const dateObj = new Date(form.value.date)
          if (!isNaN(dateObj.getTime())) {
            const year = dateObj.getFullYear()
            const month = String(dateObj.getMonth() + 1).padStart(2, '0')
            const day = String(dateObj.getDate()).padStart(2, '0')
            form.value.date = `${year}-${month}-${day}`
          }
        }
        
        let result
        if (dialogType.value === 'add') {
          // 创建新记录
          const { record_id, ...createData } = form.value
          result = await attendanceStore.createAttendanceRecord(createData)
        } else {
          // 更新记录
          const { record_id, ...updateData } = form.value
          result = await attendanceStore.updateAttendanceRecord(record_id, updateData)
        }
        
        if (result) {
          dialogVisible.value = false
          ElMessage.success(
            dialogType.value === 'add' ? '新增成功' : '更新成功'
          )
          // 刷新数据
          await fetchAttendanceRecords()
        }
      } catch (error: any) {
        console.error('提交失败:', error)
        // 处理唯一性约束错误
        if (error.response?.data?.detail && error.response.data.detail.includes('已存在工号')) {
          ElMessage.error(`无法${dialogType.value === 'add' ? '新增' : '更新'}：${error.response.data.detail}`)
        } else {
          ElMessage.error(`${dialogType.value === 'add' ? '新增' : '更新'}失败`)
        }
      }
    }
  })
}

// 处理Excel文件上传
const handleExcelChange = async (file: any) => {
  try {
    // 指定字段映射
    const headerMap = {
      '工号': 'employee_id',
      '日期': 'date',
      '星期': 'weekday',
      '早上上班': 'morning_on_duty',
      '中午下班': 'noon_off_duty',
      '下午下班': 'afternoon_off_duty',
      '晚上下班': 'night_off_duty',
      '中午工时': 'noon_work_hours',
      '下午工时': 'afternoon_work_hours',
      '白班总工时': 'day_total_work_hours',
      '晚上工时': 'night_work_hours',
      '加班工时': 'overtime_hours',
      '考勤类型': 'attendance_type_id',
      '加班类型': 'overtime_type'
    }
    
    const data = await readExcelFile(file.raw, headerMap, '打卡数据合并')
    
    // 验证数据
    const requiredFields = [
      'employee_id',
      'date',
      'weekday',
      'attendance_type_id'
    ]
    if (!validateImportData(data, requiredFields)) {
      return
    }
    
    // 转换数据格式
    const formattedRecords = data.map(item => {
      // 处理日期格式，统一为 YYYY-MM-DD
      let formattedDate = item.date
      if (formattedDate) {
        // 尝试解析各种可能的日期格式
        const dateObj = new Date(formattedDate)
        if (!isNaN(dateObj.getTime())) {
          // 日期有效，格式化为 YYYY-MM-DD
          const year = dateObj.getFullYear()
          const month = String(dateObj.getMonth() + 1).padStart(2, '0')
          const day = String(dateObj.getDate()).padStart(2, '0')
          formattedDate = `${year}-${month}-${day}`
        }
      }
      
      return {
        employee_id: String(item.employee_id),
        date: formattedDate,
        weekday: item.weekday,
        morning_on_duty: item.morning_on_duty || '',
        noon_off_duty: item.noon_off_duty || '',
        afternoon_off_duty: item.afternoon_off_duty || '',
        night_off_duty: item.night_off_duty || '',
        noon_work_hours: Number(item.noon_work_hours || 0),
        afternoon_work_hours: Number(item.afternoon_work_hours || 0),
        day_total_work_hours: Number(item.day_total_work_hours || 0),
        night_work_hours: Number(item.night_work_hours || 0),
        overtime_hours: Number(item.overtime_hours || 0),
        attendance_type_id: Number(item.attendance_type_id),
        overtime_type: Number(item.overtime_type || 0)
      }
    })
    
    // 批量创建考勤记录
    const result = await attendanceStore.batchCreateAttendanceRecords(formattedRecords)
    
    if (result) {
      // 刷新数据
      await fetchAttendanceRecords()
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败: ' + (error instanceof Error ? error.message : String(error)))
  }
}

// 重置筛选条件
const resetFilters = () => {
  dateRange.value = null
  selectedEmployee.value = ''
  selectedAttendanceType.value = null
  selectedOvertimeType.value = null
  handleSearch()
}

// 处理表格多选变化
const handleSelectionChange = (val: AttendanceRecord[]) => {
  multipleSelection.value = val
}

// 导出Excel功能
const handleExport = () => {
  try {
    // 准备导出数据
    const exportData = filteredRecords.value.map(record => {
      // 获取考勤类型名称
      const attendanceTypeName = getAttendanceTypeName(record.attendance_type_id)
      // 获取加班类型名称
      const overtimeTypeName = getOvertimeTypeName(record.overtime_type)
      
      return {
        '工号': record.employee_id,
        '姓名': record.employee_name || '',
        '日期': record.date,
        '星期': record.weekday,
        '早上上班': record.morning_on_duty,
        '中午下班': record.noon_off_duty,
        '下午下班': record.afternoon_off_duty,
        '晚上下班': record.night_off_duty,
        '中午工时': record.noon_work_hours,
        '下午工时': record.afternoon_work_hours,
        '白班总工时': record.day_total_work_hours,
        '晚上工时': record.night_work_hours,
        '加班工时': record.overtime_hours,
        '考勤类型': attendanceTypeName,
        '加班类型': overtimeTypeName
      }
    })
    
    if (exportData.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }
    
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '考勤记录')
    
    // 设置列宽
    const colWidths = [
      { wpx: 100 }, // 工号
      { wpx: 100 }, // 姓名
      { wpx: 100 }, // 日期
      { wpx: 80 },  // 星期
      { wpx: 100 }, // 早上上班
      { wpx: 100 }, // 中午下班
      { wpx: 100 }, // 下午下班
      { wpx: 100 }, // 晚上下班
      { wpx: 80 },  // 中午工时
      { wpx: 80 },  // 下午工时
      { wpx: 80 },  // 白班总工时
      { wpx: 80 },  // 晚上工时
      { wpx: 80 },  // 加班工时
      { wpx: 100 }, // 考勤类型
      { wpx: 80 }   // 加班类型
    ]
    worksheet['!cols'] = colWidths
    
    // 导出文件
    const now = new Date()
    const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`
    const filename = `考勤记录_${dateStr}.xlsx`
    XLSX.writeFile(workbook, filename)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error instanceof Error ? error.message : String(error)))
  }
}

// 批量编辑相关
const batchEditDialogVisible = ref(false)
const batchFormRef = ref<FormInstance>()
const batchForm = ref({
  attendance_type_id: 0,
  overtime_type: 0,
  noon_work_hours: 0,
  afternoon_work_hours: 0,
  day_total_work_hours: 0,
  night_work_hours: 0,
  overtime_hours: 0,
  morning_on_duty: '',
  noon_off_duty: '',
  afternoon_off_duty: '',
  night_off_duty: ''
})
const batchFields = ref({
  attendanceType: false,
  overtimeType: false,
  workHours: false,
  dutyTimes: false
})

// 打开批量编辑对话框
const handleBatchEdit = () => {
  if (!hasSelection.value) {
    ElMessage.warning('请先选择要编辑的记录')
    return
  }
  
  // 重置表单
  batchForm.value = {
    attendance_type_id: 0,
    overtime_type: 0,
    noon_work_hours: 0,
    afternoon_work_hours: 0,
    day_total_work_hours: 0,
    night_work_hours: 0,
    overtime_hours: 0,
    morning_on_duty: '',
    noon_off_duty: '',
    afternoon_off_duty: '',
    night_off_duty: ''
  }
  batchFields.value = {
    attendanceType: false,
    overtimeType: false,
    workHours: false,
    dutyTimes: false
  }
  
  // 显示对话框
  batchEditDialogVisible.value = true
}

// 确认批量编辑
const confirmBatchEdit = async () => {
  // 检查是否选择了至少一个字段
  if (!batchFields.value.attendanceType && 
      !batchFields.value.overtimeType && 
      !batchFields.value.workHours && 
      !batchFields.value.dutyTimes) {
    ElMessage.warning('请至少选择一个要修改的字段')
    return
  }
  
  try {
    // 准备批量更新的数据
    const updateData: { [key: string]: any } = {}
    
    // 添加考勤类型
    if (batchFields.value.attendanceType) {
      updateData.attendance_type_id = batchForm.value.attendance_type_id
    }
    
    // 添加加班类型
    if (batchFields.value.overtimeType) {
      updateData.overtime_type = batchForm.value.overtime_type
    }
    
    // 添加工时相关字段
    if (batchFields.value.workHours) {
      updateData.noon_work_hours = batchForm.value.noon_work_hours
      updateData.afternoon_work_hours = batchForm.value.afternoon_work_hours
      updateData.day_total_work_hours = batchForm.value.day_total_work_hours
      updateData.night_work_hours = batchForm.value.night_work_hours
      updateData.overtime_hours = batchForm.value.overtime_hours
    }
    
    // 添加上下班时间字段
    if (batchFields.value.dutyTimes) {
      updateData.morning_on_duty = batchForm.value.morning_on_duty
      updateData.noon_off_duty = batchForm.value.noon_off_duty
      updateData.afternoon_off_duty = batchForm.value.afternoon_off_duty
      updateData.night_off_duty = batchForm.value.night_off_duty
    }
    
    // 获取选中记录的ID
    const recordIds = multipleSelection.value.map(record => record.record_id)
    
    // 显示加载中
    const loadingInstance = ElMessage.info({
      message: '批量更新中，请稍候...',
      duration: 0,
      showClose: false
    })
    
    // 调用批量更新API
    const result = await attendanceStore.batchUpdateAttendanceRecords(recordIds, updateData)
    
    // 关闭加载中
    loadingInstance.close()
    
    // 显示结果
    if (result.updated_count === result.total_count) {
      ElMessage.success(result.message)
    } else {
      ElMessage.warning(result.message)
    }
    
    // 关闭对话框
    batchEditDialogVisible.value = false
    
    // 刷新数据
    await fetchAttendanceRecords()
    
    // 清空选择
    multipleSelection.value = []
  } catch (error) {
    console.error('批量更新失败:', error)
    ElMessage.error('批量更新失败: ' + (error instanceof Error ? error.message : String(error)))
  }
}

// 详情视图相关
const route = useRoute()
const router = useRouter()
const isDetailMode = ref(false)
const recordDetail = ref<AttendanceRecord>({
  record_id: 0,
  employee_id: '',
  employee_name: '',
  date: '',
  weekday: '',
  morning_on_duty: '',
  noon_off_duty: '',
  afternoon_off_duty: '',
  night_off_duty: '',
  noon_work_hours: 0,
  afternoon_work_hours: 0,
  day_total_work_hours: 0,
  night_work_hours: 0,
  overtime_hours: 0,
  attendance_type_id: 0,
  overtime_type: 0
})

// 获取考勤记录详情
const fetchRecordDetail = async (id: string) => {
  try {
    const response = await axios.get(`http://localhost:8000/api/attendance-records/${id}`)
    if (response.data) {
      recordDetail.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取考勤记录详情失败')
    console.error('获取考勤记录详情失败:', error)
  }
}

// 返回列表视图
const backToList = () => {
  isDetailMode.value = false
  router.push('/attendance-records')
}

// 查看详情
const viewDetail = (row: AttendanceRecord) => {
  recordDetail.value = { ...row }
  isDetailMode.value = true
  // 更新URL但不触发路由变化
  const newUrl = `/attendance-records?id=${row.record_id}&mode=detail`
  window.history.pushState({}, '', newUrl)
}

// 获取考勤类型标签样式
const getAttendanceTypeTagType = (typeId: number) => {
  const type = attendanceTypes.value.find(t => t.type_id === typeId)
  const typeName = type ? type.type_name : ''
  
  const typeMap: { [key: string]: string } = {
    '正常': 'success',
    '迟到': 'warning',
    '早退': 'warning',
    '旷工': 'danger',
    '请假': 'info'
  }
  return typeMap[typeName] || ''
}

// 获取加班类型标签样式
const getOvertimeTypeTagType = (type: number) => {
  const typeMap: { [key: number]: string } = {
    0: 'info',
    1.5: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[type] || ''
}

// 检查URL是否包含详情模式参数
const checkDetailMode = () => {
  const id = route.query.id as string
  const mode = route.query.mode as string
  
  if (id && mode === 'detail') {
    fetchRecordDetail(id)
    isDetailMode.value = true
  } else {
    isDetailMode.value = false
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchAttendanceRecords(),
    fetchEmployees(),
    fetchAttendanceTypes()
  ])
  
  // 检查是否是详情模式
  checkDetailMode()
})

// 批量删除处理
const handleBatchDelete = () => {
  if (!hasSelection.value) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  batchDeleteDialogVisible.value = true
}

// 确认批量删除
const confirmBatchDelete = async () => {
  try {
    // 获取选中记录的ID
    const recordIds = multipleSelection.value.map(record => record.record_id)
    
    // 显示加载中
    const loadingInstance = ElMessage.info({
      message: '批量删除中，请稍候...',
      duration: 0,
      showClose: false
    })
    
    // 使用批量删除API，一次性删除所有选中记录
    const result = await attendanceStore.batchDeleteAttendanceRecords(recordIds)
    
    // 关闭加载中
    loadingInstance.close()
    
    // 显示结果
    if (result.deleted_count === result.total_count) {
      ElMessage.success(`成功删除 ${result.deleted_count} 条记录`)
    } else {
      ElMessage.warning(`操作完成，成功删除 ${result.deleted_count} 条记录，${result.total_count - result.deleted_count} 条记录删除失败`)
    }
    
    // 关闭对话框
    batchDeleteDialogVisible.value = false
    
    // 刷新数据
    await fetchAttendanceRecords()
    
    // 清空选择
    multipleSelection.value = []
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败: ' + (error instanceof Error ? error.message : String(error)))
  }
}
</script>

<style scoped>
.attendance-records-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.attendance-record-detail {
  padding: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-descriptions {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-bar .left {
  display: flex;
  gap: 10px;
}

.operation-bar .right {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.excel-upload {
  display: inline-block;
}

.filter-bar {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 